package com.example.safeassistan.home.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.CheckLogSecond;
import com.example.safeassistan.home.adapter.CheckRecordFragmentAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.adapter.RiskCheckTableSelectedListAdapter;
import com.example.safeassistan.risk.model.ChecktableListModel;
import com.example.safeassistan.risk.model.RiskDetailCheckLogModel;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.ViewPagerForScrollView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class RiskDetailCheckLogFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private LinearLayout llCheckTable,llCheckResult,llNodata;
    private TextView tvCheckTable,tvCheckResult;
    private ViewPagerForScrollView pager;
    private PopupWindow popupWindow=null;
    private CheckRecordFragmentAdapter adapter;
    private List<RiskDetailCheckLogModel.ResultDTO.RecordsDTO> data;
    private ChecktableListModel checktableListModel;
    private SmartRefreshLayout refresh;
    private RecyclerView rcView;
    private int currentPage=1;
    private int count=0;


    private String riskPointId="";
    private int riskLevel=-1;
    private String checkTableId="";
    private String tableResult="";

    public RiskDetailCheckLogFragment(ViewPagerForScrollView pager,String riskPointId,int riskLevel) {
        this.pager = pager;
        this.riskPointId=riskPointId;
        this.riskLevel=riskLevel;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.riskdetail_checklog_fragment, container, false);
            pager.setObjectForPosition(view,1);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        refresh=view.findViewById(R.id.refresh);
        llCheckResult=view.findViewById(R.id.llCheckResult);
        llCheckTable=view.findViewById(R.id.llCheckTable);
        tvCheckTable=view.findViewById(R.id.tvCheckTable);
        tvCheckResult=view.findViewById(R.id.tvCheckResult);
        llNodata=view.findViewById(R.id.llNodata);
        llCheckTable.setOnClickListener(this);
        llCheckResult.setOnClickListener(this);
        rcView=view.findViewById(R.id.rcView);

        setView();
        getData();
        getTabletListData();
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("riskPointId",riskPointId);//选择类型 1 我的 2 部门
            if (checkTableId!=null&&!checkTableId.equals("")){
                map.put("checkTableId",checkTableId);//检查表id
            }
            if (tableResult!=null&&!tableResult.equals("")){
                map.put("tableResult",tableResult);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.getRiskCheckedRecordList, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskDetailCheckLogModel.class);
                        if (obj instanceof RiskDetailCheckLogModel) {
                            RiskDetailCheckLogModel model=(RiskDetailCheckLogModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    data=model.getResult().getRecords();
                                    adapter=new CheckRecordFragmentAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            CheckLogSecond.actionStart(context,data.get(position).getId(),
                                                    data.get(position).getCheckTableId(),
                                                    data.get(position).getDefRecordId(),riskPointId);
                                        }
                                    });
                                } else {
                                    llNodata.setVisibility(View.VISIBLE);
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) { }

    @Override
    protected void onFragmentFirstVisible() { }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llCheckResult:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_risk_check_result,null);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="";
                        popupWindow.dismiss();
                        tvCheckResult.setText("检查结果");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                TextView tvBig=inflate1.findViewById(R.id.tvBig);
                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="1";
                        popupWindow.dismiss();
                        tvCheckResult.setText("已通过");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvBigger=inflate1.findViewById(R.id.tvBigger);
                tvBigger.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="2";
                        popupWindow.dismiss();
                        tvCheckResult.setText("未通过");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                TextView tvCommon=inflate1.findViewById(R.id.tvCommon);
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="3";
                        popupWindow.dismiss();
                        tvCheckResult.setText("存在隐患");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();

                    }
                });
                TextView tvLow=inflate1.findViewById(R.id.tvLow);
                tvLow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tableResult="0";
                        popupWindow.dismiss();
                        tvCheckResult.setText("未涉及");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(tvCheckResult,0,-100);
                break;
            case R.id.llCheckTable:
               View inflate2 = LayoutInflater.from(context).inflate(R.layout.layout_popuwindow_department,null);
                TextView tvAlls=inflate2.findViewById(R.id.tvAll);
                tvAlls.setText("检查表筛选");
                tvAlls.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkTableId="";
                        popupWindow.dismiss();
                        tvCheckTable.setText("检查表筛选");
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.gray3));
                        getData();
                    }
                });
                RecyclerView rcView=inflate2.findViewById(R.id.rcView);
                RiskCheckTableSelectedListAdapter adapter=new RiskCheckTableSelectedListAdapter(checktableListModel.getResult());
                rcView.setAdapter(adapter);
                rcView.setLayoutManager(new LinearLayoutManager(context));
                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        checkTableId=checktableListModel.getResult().get(position).getId();
                        popupWindow.dismiss();
                        tvCheckTable.setText(checktableListModel.getResult().get(position).getTableName());
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(tvCheckTable,0,-100);
                break;
        }
    }

    public void getTabletListData(){
        new HttpRequest(context).doGet(UrlConstants.getAllTableList, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), ChecktableListModel.class);
                        if (obj instanceof ChecktableListModel) {
                            checktableListModel=(ChecktableListModel) obj;
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}